package servlet;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取客户端发来的数据
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 2. 验证请求中的参数是否有效
        resp.setContentType("text/html; charset=utf8");
        if(username == null || username.length() == 0 || password == null || password.length() == 0) {
            resp.getWriter().write("您输入的账户名或密码错误!");
            return;
        }
        // 根据username 从数据库中查询User对象,验证账号和密码是否正确
        UserDao userDao = new UserDao();
        User user = userDao.getUserByUsername(username);
        if(user == null) {
            //用户不存在
            resp.getWriter().write("您输入的用户名或密码不正确!");
            return;
        }
        if(!user.getPassword().equals(password)) {
            resp.getWriter().write("您输入的用户名或密码不正确!");
            return;
        }

        // 3. 创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);

        // 4. 登录成功,跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 根据 session 和 session中的user 判断用户是否处于登录状态
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 会话不存在,用户当前未登录
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // user 对象不存在,用户当前处于未登录状态
            resp.setStatus(403);
            return;
        }

        // 2. 用户当前处于登录状态,返回 200状态码
        resp.setStatus(200);
    }
}
